package com.sike.netty.im.client.handler;

import com.sike.netty.im.common.command.HearBeatRequestCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 心跳 handler
 *
 * @author chenssy
 * @date 2023/09/25
 */
@Slf4j
public class HearBeatTimerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送心跳
        scheduleSendHeartBeat(ctx);

        super.channelActive(ctx);
    }

    /**
     * 定期发送心跳给服务端
     * @param ctx
     */
    private void scheduleSendHeartBeat(ChannelHandlerContext ctx) {
        ctx.executor().scheduleAtFixedRate(() -> {
            if (ctx.channel().isActive()) {
                log.info("{},发送心跳数据..",ctx.channel());
                Message message = MessageBuilder.buildMessage(new HearBeatRequestCommand("hello"),null,null);
                ctx.writeAndFlush(message);
            }
        },1,5, TimeUnit.SECONDS);
    }
}
